package com.tgy.leetcode.backtracking;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: tgy
 * @Date: 2020-11-22 15:47
 */
public class _15_三数之和_02 {

    public List<List<Integer>> threeSum(int[] nums) {

        List<List<Integer>> lists = new LinkedList<>();
        if (nums == null || nums.length == 0) {

            return lists;
        }

        Arrays.sort(nums);

        int count = 0;


        for (int i = 0; nums[i] <= 0 && i < nums.length - 2; i++) {

            // 去除重复的
            if (i > 0 && nums[i] == nums[i - 1]) {

                continue;
            }

            int left = i + 1, right = nums.length -1;

            while (left < right) {

                count++;
                int sum = nums[i] + nums[left] + nums[right];

                if (sum == 0) {

                    lists.add(Arrays.asList(nums[i],nums[left],nums[right]));

                    left++;
                    right--;

                    while (left < right && nums[left] == nums[left - 1]) {
                        left++;
                    }

                    while (left < right && nums[right] == nums[right + 1]) {

                        right--;
                    }

                }else if (sum < 0) {

                    left++;

                }else {

                    right--;
                }

            }

        }


        System.out.println(count);

        return lists;
    }


}
